<template>
  <div id="page-userManage">
    <!-- 查询 -->
    <div class="page-search-list">
      <el-form label-position="left" :model="search_from" :inline="true">
        <el-form-item
          v-for="(item, i) in search_info"
          :label="item.label"
          :key="i"
          style="margin-bottom: 5px;"
        >
          <template v-if="item.prop === 'cid'">
            <select-community
              :cid.sync="search_from[item.prop]"
              :pid.sync="search_from.pid"
              :bid.sync="search_from.bid"
              :sid.sync="search_from.sid"
            ></select-community>
          </template>
          <template v-else-if="item.prop === 'sex'">
            <select-sex :sex.sync="search_from[item.prop]"></select-sex>
          </template>
          <template v-else>
            <el-input
              v-model="search_from[item.prop]"
              size="small"
              :placeholder="`请输入${item.label}`"
            ></el-input>
          </template>
        </el-form-item>
        <el-form-item>
          <el-button class="el-icon-search" size="small" @click.native="search">
            搜索
          </el-button>
          <el-button
            type="primary"
            class="el-icon-refresh"
            size="small"
            @click.native="resetSearchFields"
          >
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 按钮 -->
    <div class="page-botton-list">
      <el-button
        type="warning"
        plain
        class="el-icon-plus"
        size="mini"
        @click="add_user_dialog = true"
      >
        新增
      </el-button>
      <el-button
        type="danger"
        plain
        class="el-icon-delete"
        size="mini"
        :disabled="is_delete"
        @click="deleteUser"
        key="delete_arr_button"
      >
        删除
      </el-button>
      <ExportExcel
        style="margin-left: 0.625rem;"
        :id="'tableDataId'"
        :label="'导出'"
        :multipleSelection="multiple_selection"
        :tableData="tableData"
        :tableInfo="tableInfo"
      ></ExportExcel>
    </div>
    <!-- 表格 -->
    <div class="page-table">
      <el-table
        ref="tableDataRef"
        :data="tableData"
        style="width: 100%;"
        id="tableDataId"
        @selection-change="selectTabel"
      >
        <el-table-column type="selection" />
        <el-table-column
          v-for="(column, i) in tableInfo"
          :key="i"
          :label="column.label"
          align="center"
          :width="
            column.prop === 'age' ||
            column.prop === 'sex' ||
            column.prop === 'name'
              ? '60px'
              : column.prop === 'isDel'
              ? '140px'
              : null
          "
        >
          <template slot-scope="scope">
            <template v-if="column.prop === 'isDel'">
              <el-switch
                :value="scope.row[column.prop]"
                active-text="正常"
                inactive-text="失效"
                :active-value="0"
                :inactive-value="1"
                @change="changeStatus(scope.row)"
              ></el-switch>
            </template>
            <template v-else-if="column.prop === 'sex'">
              <el-tag>
                {{
                  scope.row[column.prop] === 'FEMALE'
                    ? '女'
                    : scope.row[column.prop] === 'MALE'
                    ? '男'
                    : '未知'
                }}
              </el-tag>
            </template>
            <template v-else>{{ scope.row[column.prop] }}</template>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100px" align="center">
          <template slot-scope="scope">
            <el-link
              type="primary"
              icon="el-icon-edit"
              @click="changeUerInfo(scope.row)"
            >
              修改
            </el-link>
            <el-link
              style="margin: 0 15px;"
              type="primary"
              icon="el-icon-delete"
              @click="deleteUser(scope.row, true)"
            >
              删除
            </el-link>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageCount"
        :page-sizes="[10, 100, 200, 300, 400]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        class="upload-list-pagination"
      ></el-pagination>
    </div>

    <!-- 添加/修改 弹窗 -->
    <el-dialog
      :title="is_change_travel ? '修改居民信息' : '添加居民'"
      :visible.sync="add_user_dialog"
      :append-to-body="true"
      width="40%"
    >
      <el-form
        :model="dialog_from"
        label-position="left"
        :rules="rules"
        ref="addUserDialogRef"
      >
        <el-form-item
          v-for="(item, i) in dialog_info"
          :key="i"
          :label="item.label"
          label-width="80px"
          :prop="item.prop"
        >
          <template v-if="item.prop === 'cid'">
            <select-community
              :cid.sync="dialog_from[item.prop]"
              :pid.sync="dialog_from.pid"
              :bid.sync="dialog_from.bid"
              :sid.sync="dialog_from.sid"
            ></select-community>
          </template>
          <template v-else-if="item.prop === 'age'">
            <el-input-number
              size="medium"
              v-model="dialog_from[item.prop]"
            ></el-input-number>
          </template>
          <template v-else-if="item.prop === 'sex'">
            <select-sex :sex.sync="dialog_from[item.prop]"></select-sex>
          </template>
          <template v-else-if="item.prop === 'address'">
            <select-address
              :address.sync="dialog_from.address"
              ref="liveAddressRef"
            ></select-address>
          </template>
          <template v-else-if="item.prop === 'isDel'">
            <el-switch
              v-if="is_change_travel"
              v-model="dialog_from['isDel']"
              active-text="正常"
              inactive-text="失效"
              :active-value="0"
              :inactive-value="1"
            ></el-switch>
            <el-tag v-else>正常</el-tag>
          </template>
          <template v-else>
            <el-input
              :maxlength="item.prop === 'tel' ? 11 : null"
              v-model="dialog_from[item.prop]"
              size="small"
            ></el-input>
          </template>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelDialog">取 消</el-button>
        <el-button
          type="primary"
          v-if="is_change_travel"
          @click="uploadChangeTravel"
        >
          确定修改
        </el-button>
        <el-button v-else type="primary" @click="addClick">
          确定添加
        </el-button>
      </div>
    </el-dialog>

    <!-- 删除弹窗 -->
    <el-dialog
      title="提示"
      :visible.sync="delete_dialog_visible"
      width="30%"
      center
      :append-to-body="true"
    >
      <div style="text-align: center;">
        是否删除以下用户
        <li v-for="(item, i) in delete_user_arr" :key="i">
          {{ i + 1 + '.' + item.name + '（' + item.account + '）' }}
        </li>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="falsedeleteUser">取 消</el-button>
        <el-button type="primary" @click="truedeleteUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改弹窗 -->
    <el-dialog
      title="提示"
      :visible.sync="change_dialog_visible"
      width="30%"
      center
      :append-to-body="true"
    >
      <div style="text-align: center;">
        是否修改{{
          this.change_user.name + '（' + this.change_user.account + '）'
        }}的账户状态
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="falseChangeUser">
          取 消
        </el-button>
        <el-button type="primary" @click="trueChangeUser">
          确 定
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { isNull, assignAttr, clearnNull } from '@/utils/tool'
import {
  getList,
  changeIsDel,
  trueDelete,
  addUser,
  checkoutRegister,
} from '@/api/admin/user'
import { rules } from '@/utils/rules'
export default {
  computed: {
    is_delete() {
      return !this.multiple_selection.length > 0
    },
  },
  watch: {
    search_from: {
      handler(val) {
        console.debug(val)
      },
    },
    add_user_dialog: {
      handler(val) {
        if (!val) {
          this.dialog_from = {
            cid: '',
            pid: '',
            bid: '',
            sid: '',
            name: '',
            age: '',
            sex: '',
            tel: '',
            email: '',
            address: '',
            isDel: '',
          }
          this.$refs.liveAddressRef[0].resetAddress()
        }
      },
    },
    delete_dialog_visible: {
      handler(val) {
        if (!val) {
          this.delete_user_arr = []
          this.$refs.tableDataRef.clearSelection()
        }
      },
    },
    change_dialog_visible: {
      handler(val) {
        if (!val) {
          this.change_user = {
            name: '',
            account: '',
            id: '',
            isDel: null,
          }
        }
      },
      immediate: true,
    },
    dialog_from: {
      handler(val) {
        // console.debug(val)
        if (!this.add_user_dialog && this.$refs.addUserDialogRef)
          this.$refs.addUserDialogRef.clearValidate()
      },
      deep: true,
      immediate: true,
    },
    'dialog_from.tel': {
      handler(val) {
        if (!this.$refs.addUserDialogRef) return
        if (val.length === 11) {
          // 校验账号是否已注册
          checkoutRegister(val).then((res) => {
            if (res.msg == '用户已存在') {
              this.$message({
                message: '该电话已被注册！',
                type: 'warning',
              })
            }
          })
        }
      },
      immediate: true,
    },
    change_user: {
      handler(val) {
        // console.log(val)
      },
      deep: true,
      immediate: true,
    },
  },
  data() {
    return {
      total: 10, //总数据
      pageCount: 1, // 页数
      // currentPage: 1,
      pageSize: 10, // 页的大小
      // 查询信息
      search_from: {
        cid: '',
        pid: '',
        bid: '',
        sid: '',
        name: '', // 名称
        sex: '', // 性别
      },
      search_info: {
        cid: { label: '社区', prop: 'cid' },
        name: { label: '姓名', prop: 'name' },
        sex: { label: '性别', prop: 'sex' },
      },
      tableInfo: {
        account: { label: '账号', prop: 'account' },
        fullName: { label: '社区', prop: 'fullName' },
        name: { label: '姓名', prop: 'name' },
        age: { label: '年龄', prop: 'age' },
        sex: { label: '性别', prop: 'sex' },
        tel: { label: '电话', prop: 'tel' },
        email: { label: '邮箱', prop: 'email' },
        address: { label: '地址', prop: 'address' },
        isDel: { label: '状态', prop: 'isDel' },
      },
      tableData: [],
      multiple_selection: [], // 表格选择
      add_user_dialog: false, // 弹窗是否可见
      is_change_travel: false, // 是否修改
      dialog_from: {
        cid: '',
        pid: '',
        bid: '',
        sid: '',
        name: '',
        age: '',
        sex: '',
        tel: '',
        email: '',
        address: '',
        isDel: '',
      },
      dialog_info: {
        cid: { label: '社区', prop: 'cid' },
        name: { label: '姓名', prop: 'name' },
        age: { label: '年龄', prop: 'age' },
        sex: { label: '性别', prop: 'sex' },
        tel: { label: '电话', prop: 'tel' },
        email: { label: '邮箱', prop: 'email' },
        address: { label: '地址', prop: 'address' },
        isDel: { label: '状态', prop: 'isDel' },
      },
      delete_dialog_visible: false, //删除弹窗是否可见
      delete_user_arr: [], // 删除数组
      rules: {
        ...rules,
        tel: [{ required: true, message: '请输入电话号码', trigger: 'blur' }],
      },
      change_dialog_visible: false,
      change_user: {
        name: '',
        account: '',
        id: '',
        isDel: null,
      },
    }
  },
  created() {
    this.search()
  },
  methods: {
    /* 请求 */
    /* DOM 操作 */
    // 搜索
    search() {
      // console.debug('搜索条件：',this.search_from)
      let data = {
        ...this.search_from,
        pageSize: this.pageSize,
        pageCount: this.pageCount,
      }
      data = clearnNull(data)
      console.log('data', data)
      getList(data).then((res) => {
        this.tableData = res.data.content
        this.currentPage = res.data.number
        this.total = res.data.totalElements
      })
    },
    // 清空搜索条件
    resetSearchFields() {
      this.search_from = {
        cid: null,
        pid: null,
        bid: null,
        sid: null,
        name: null,
        sex: null,
      }
      console.log(this.search_from)
      this.pageCount = 1
      this.pageSize = 10
      this.currentPage = 1
      this.search()
    },
    // 表格选择
    selectTabel(val) {
      this.multiple_selection = val
    },

    addClick() {
      let data = [this.dialog_from]
      data = clearnNull(data)
      addUser(data).then((res) => {
        this.search()
        this.add_user_dialog = false
        this.$message({
          message: '添加成功',
          type: 'success',
        })
      })
    },

    // 点击 取消 最外弹窗
    cancelDialog() {
      this.add_user_dialog = false
    },

    // 点击修改
    changeUerInfo(row) {
      this.add_user_dialog = true
      this.is_change_travel = true
      // 查询
      console.debug(row)
      assignAttr(row, this.dialog_from)
    },

    // 上传修改
    uploadChangeTravel() {
      this.add_user_dialog = false
      console.log('确认修改', this.dialog_from)
      this.$message({
        message: '修改成功',
        type: 'success',
      })
    },

    // 删除
    deleteUser(row, flag) {
      console.log(row)
      this.delete_dialog_visible = true
      if (flag) {
        // 单个删除
        let user = {
          id: row.id,
          name: row.name,
          account: row.account,
        }
        this.delete_user_arr.push(user)
        console.debug('删除单个')
      } else {
        this.multiple_selection.forEach((item) => {
          let user = {
            id: item.id,
            name: item.name,
            account: item.account,
          }
          this.delete_user_arr.push(user)
        })
        console.debug('删除数组')
      }
    },
    falsedeleteUser() {
      this.delete_dialog_visible = false
      this.$message('已取消删除')
    },
    truedeleteUser() {
      let arr = []
      this.delete_user_arr.forEach((item) => {
        arr.push(item.id)
      })
      trueDelete(arr).then((res) => {
        this.delete_dialog_visible = false
        this.$message({
          message: '删除成功',
          type: 'success',
        })
        this.search()
      })
    },

    // 修改状态
    changeStatus(row) {
      this.change_dialog_visible = true
      this.change_user.name = row.name
      this.change_user.id = row.id
      this.change_user.account = row.account
      this.change_user.isDel = row.isDel === 1 ? 0 : 1
    },
    trueChangeUser() {
      let params = this.change_user.isDel
      let data = [this.change_user.id]
      changeIsDel(params, data).then((res) => {
        this.$message({
          message: '修改成功',
          type: 'success',
        })
        this.change_dialog_visible = false
        this.search()
      })
    },
    falseChangeUser() {
      this.change_dialog_visible = false
    },

    handleSizeChange(val) {
      this.pageSize = val
      this.search()
    },
    handleCurrentChange(val) {
      this.pageCount = val
      this.search()
    },
  },
}
</script>

<style lang="less" scoped>
#page-userManage {
  padding: 0 0.5rem;
  .page-table {
    .el-button {
      margin: 2px 0;
    }
  }
  .el-collapse-title-div {
    display: flex;
    justify-content: space-around;
    width: 90%;
  }
  .el-form-ul {
    min-height: 2.375rem;
    border: 1px solid #dcdfe6;
  }
  /deep/.el-collapse {
    border: none;
    background-color: rgba(255, 255, 255, 0);
  }
  /deep/.el-collapse-item__content {
    padding-bottom: 0;
  }
}
.page-botton-list {
  margin-bottom: 0.625rem;
}
.ul-address-date {
  display: flex;
  .ul-address-date-item {
    flex: 1;
    margin-right: 1.25rem;
    &:last-child {
      margin-right: 0;
    }
  }
}
/deep/.el-select {
  width: 100%;
}
.address-tag {
  margin-right: 0.625rem;
  &:last-child {
    margin-right: 0;
  }
}
.upload-list-pagination {
  margin-top: 1.8rem;
  display: flex;
  justify-content: center;
}
</style>
